<?php

namespace Cblood\Sword\Database;

class Result
{
    /**
     * @var \PDOStatement
     */
    protected $result;

    public function __construct($result)
    {
        $this->result = $result;
    }

    /**
     * 返回全部查询结果
     * @param null $entity
     * @return array
     * @throws \Exception
     */
    public function all($entity = null)
    {
        if (empty($entity)) {
            return $this->result->fetchAll(\PDO::FETCH_ASSOC);
        }

        if (class_exists($entity)) {
            $result = array();
            for ($i = 0; $i < $this->result->rowCount(); $i++) {
                $result[] = $this->result->fetchObject($entity);
            }
            return $result;
        }

        throw new \Exception('找不到对象' . $entity);
    }

    /**
     * 返回第一行查询结果
     * @param null $entity
     * @return mixed
     * @throws \Exception
     */
    public function first($entity = null)
    {
        if (empty($entity)) {
            return $this->result->fetch(\PDO::FETCH_ASSOC);
        } elseif (class_exists($entity)) {
            return $this->result->fetchObject($entity);
        }

        throw new \Exception('找不到对象' . $entity);
    }

    /**
     * 查询的语句
     * @return string
     */
    public function sql()
    {
        return $this->result->queryString;
    }

    /**
     * 返回查询结果行数
     * @return int
     */
    public function count()
    {
        return $this->result->rowCount();
    }
}